package com.application.api;

import com.aliyuncs.exceptions.ClientException;
import com.application.api.entity.ResultEntity;
import com.application.common.Api;
import com.application.common.utils.SmsUtil;
import com.application.common.utils.VerifyKit;
import com.application.service.UserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.platform.annotation.Controller;
import com.platform.constant.ConstantInit;
import com.platform.interceptor.AuthInterceptor;
import com.platform.interceptor.LoginInterceptor;
import com.platform.interceptor.ParamPkgInterceptor;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.upload.UploadService;
import com.platform.mvc.user.User;
import com.platform.mvc.user.UserValidator;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理
 */
@Controller("/api/user")
public class UserApiController extends BaseController {

    @SuppressWarnings("unused")
    private static Logger log = Logger.getLogger(UserApiController.class);


    UserService userService;
    UploadService uploadService;

    public static final String path_root = "files/upload/user/";


    /**
     * @title 默认列表
     */
    public void index() {
//        List<User> userList = User.dao.find("select * from pt_user");
//        renderJson(userList);
        paging(ConstantInit.db_dataSource_main, splitPage, User.sqlId_splitPageSelect, User.sqlId_splitPageFrom);
        renderJson(new ResultEntity(splitPage.getList()));
    }


    /**
     * @param passOld|旧密码|String|必填
     * @param passNew|新密码|String|必填
     * @title 密码变更
     * @respBody {
     * "code": 200,
     * "data": null,
     * "description": "密码修改成功"
     * }
     */
    @Deprecated
    public void changePass() {
        String passOld = getPara("oldPass");
        String passNew = getPara("newPass");

        String id = super.getCUserIds();
        String password = super.getCUser().getPassword();
        boolean f = password.equals(DigestUtils.md5Hex(passOld)) ?
                Db.update("update pt_user set password = ? where id = ?", DigestUtils.md5Hex(passNew), id) > 0 :
                false;

        if (f) {
            renderJson(new ResultEntity(HttpStatus.SC_OK, "密码修改成功"));
        } else {
            renderJson(new ResultEntity(HttpStatus.SC_INTERNAL_SERVER_ERROR, "密码修改失败"));
        }
    }


    /**
     * @param newMobile|新手机号|String|必填
     * @param valicode|验证码|String|必填（暂未使用）
     * @title 修改手机
     */
    public void changeMobile() {
        String newsMobile = getPara("newMobile");
        String valicode = getPara("valicode");
        if (!SmsUtil.verify(newsMobile, valicode)) {
            renderJson(new ResultEntity(HttpStatus.SC_BAD_REQUEST, "验证码错误"));
            return;
        }

        boolean f = User.dao.updateMobile(super.getCUserIds(), newsMobile);

        if (f) {
            //renderJson(new ResultEntity(HttpStatus.SC_OK, "修改成功"));
            User.cacheRemove(super.getCUserIds());
            forwardAction("/api/user/info");
        } else {
            renderJson(new ResultEntity(HttpStatus.SC_INTERNAL_SERVER_ERROR, "修改失败"));
        }
    }

    /**
     * @param username|用户名|String|必填
     * @param password|密码|String|必填(新密码）
     * @param valicode|验证码|String|必填（暂未使用）
     * @title 找回密码
     */
    @Clear(LoginInterceptor.class)
    public void findPass() {
        String username = getPara("username");
        String passNew = getPara("password");
        String valicode = getPara("valicode");
        if (!VerifyKit.verify(username, valicode)) {
            renderJson(new ResultEntity(HttpStatus.SC_BAD_REQUEST, "验证码错误"));
            return;
        }

        int i = Db.update("update pt_user set password = ?, update_time =? where username = ?",
                DigestUtils.md5Hex(passNew), getDate(), username);

        if (i > 0) {
            renderJson(new ResultEntity(HttpStatus.SC_OK, "密码修改成功"));
        } else {
            renderJson(new ResultEntity(HttpStatus.SC_INTERNAL_SERVER_ERROR, "密码修改失败"));
        }

    }


    /**
     * @param username|手机|String|必填
     * @param password|密码|String|必填
     * @param sex|性别|String,        man,female| 必填
     * @param nickname|             昵称 | String| 必填
     * @param img|头像                | String| 必填
     * @title 用户注册（注册后自动跳转登陆）
     */
    @Deprecated
    @Before({UserValidator.class, Tx.class})
    @Clear({LoginInterceptor.class, AuthInterceptor.class, ParamPkgInterceptor.class})
    public void register() throws ClientException {
        String password = getPara("password");
        String username = getPara("username");
        String valicode = getPara("valicode");


        if (!SmsUtil.verify(username, valicode)) {
            renderJson(new ResultEntity(HttpStatus.SC_BAD_REQUEST, "验证码错误"));
            return;
        }

        User user = new User();
        user.set(User.column_username, username)
                .set(User.column_password, DigestUtils.md5Hex(password))
                .set("point", PropKit.get("user.register"))
                .set("mobile", username);
                /*.set(User.column_nickname, getPara("nickname"))
                .set(User.column_sex, getPara("sex"))
                .set(User.column_img, getPara("img"))
                .set(User.column_roleid, Constant.group_epUser);*/

        User.saveInfo(user);
        forwardAction(Api.user_login);

//        renderJson(new ResultEntity(HttpStatus.SC_OK, "用户注册成功", userInfo));
    }


    /**
     * @param sex|性别|String, man,female|
     * @param name|      昵称 | String|
     * @param img|头像         | String|
     * @param birthday|生日
     * @param pay_pass|支付密码
     * @title 修改用户自身信息
     */
    @Before(UserValidator.class)
    public void update() {
        User user = new User();
        user.set("sex", getPara("sex"));
        user.set("name", getPara("name"));
        user.set("update_time", new java.util.Date());
        user.set("img", getPara("img"));
        user.set("birthday", getPara("birthday"));
        user.set("pay_pass", getPara("pay_pass"));
        user.setId(super.getCUserId());

        boolean f = User.dao.updateAlternative(user);

        if (f) {
            //查询用户完整信息
            renderJson(new ResultEntity(HttpStatus.SC_OK, user, "信息修改成功"));
//            forwardAction("/api/user/info");
        } else {
            renderJson(new ResultEntity(HttpStatus.SC_BAD_REQUEST, "信息修改失败"));
        }

    }


    /*
    获取用户资料,加用户最后一次更新时间，如有ID获取该信息
     */
    @Clear({LoginInterceptor.class, AuthInterceptor.class, ParamPkgInterceptor.class})
    public void info() {
        String id = getPara() == null ? getCUserIds() : getPara();
        User user = User.dao.findById(id);
        Map<String, String> map = new HashMap<>();
        String s = user.get("mobile");
        if(StrKit.notBlank(s)){
            s = StrKit.getFormatMobile(s);
        }
        map.put("username", s);
        map.put("name", user.getName());
        map.put("img", user.get("img"));
        success(map);
    }




    /**
     * 修改支付密码
     * @param valicode
     * @param mobile
     * @param password
     */
    @Before(UserValidator.class)
    public void changePayPass(){
        User user = new User().set("pay_pass", getPara("password")).set("id", getCUserId());

        User.dao.updateAlternative(user);
        User.cacheRemove(getCUserIds());
        success(null, "支付密码修改成功");
    }


    /**
     * 修改登陆密码
     * 参数password/mobile/valicode
     */
    @Before(UserValidator.class)
    public void changeLoginPass(){
        User user = new User().set("password", DigestUtils.md5Hex(getPara("password"))).set("id", getCUserId());

        User.dao.updateAlternative(user);
        User.cacheRemove(getCUserIds());
        success(null, "密码修改成功");
    }
}


